#include "RenderView.h"
#include <QResizeEvent>
#include <QCloseEvent>
#include <QMouseEvent>
#include "RenderViewThread.h"

#include <QDebug>
RenderView::RenderView(QWidget *parent) :
    QGLWidget(parent),
    mThread(NULL),
    mLeftPressed(false),
    mShiftPressed(false)
{
  setMouseTracking(true);
  setFocusPolicy(Qt::StrongFocus);
}

RenderView::~RenderView() {}

const RenderViewThread * const RenderView::thread() const
{
  return mThread;
}

void RenderView::startRendering(unsigned int frameRateInHz)
{
  mThread = new RenderViewThread(this, frameRateInHz, false, QColor(50, 50, 50));
  connect(mThread, SIGNAL(fps(unsigned int)), this, SLOT(OnThreadFps(unsigned int)));
  mThread->resize(size());
  mThread->start();
}

void RenderView::OnThreadFps(unsigned int fps)
{
  emit this->fps(fps);
}

void RenderView::resizeEvent(QResizeEvent *e)
{
  mWidth = e->size().width();
  mHeight = e->size().height();
  mThread->resize(e->size());
}

void RenderView::closeEvent(QCloseEvent *e)
{
  mThread->stop();
  mThread->wait();
  delete mThread;
  QGLWidget::closeEvent(e);
}

void RenderView::mouseMoveEvent(QMouseEvent *e)
{
  if (mLeftPressed)
  {
    mThread->camera().pan(e->x()-mLastMousePos.x());
    //mThread->camera().tilt(e->y()-mLastMousePos.y());
    mLastMousePos = e->pos();
  }
}

void RenderView::mousePressEvent(QMouseEvent *e)
{
  mLeftPressed = e->button() == Qt::LeftButton;
  mLastMousePos = e->pos();
}

void RenderView::mouseDoubleClickEvent(QMouseEvent *e)
{
}

void RenderView::mouseReleaseEvent(QMouseEvent *e)
{
  mLeftPressed = mLeftPressed && e->button() != Qt::LeftButton;
}

void RenderView::wheelEvent(QWheelEvent *e)
{
  mThread->camera().zoom(mThread->camera().distance()-e->delta()/120);
}

void RenderView::keyPressEvent(QKeyEvent *e)
{
  mShiftPressed = e->key() == Qt::Key_Shift;
}

void RenderView::keyReleaseEvent(QKeyEvent *e)
{
  mShiftPressed = mShiftPressed && e->key() != Qt::Key_Shift;
}
